﻿#region Disclaimer/Info
///////////////////////////////////////////////////////////////////////////////////////////////////
// MetaCollection
// 
// MetaCollection is a system to provide a standard structure, permissions and metadata service
// for content organization.
//
// This project is hosted at Google Code at http://code.google.com/p/metacollection/
//
// This project is licensed under the BSD license.  See the License.txt file for more information.
///////////////////////////////////////////////////////////////////////////////////////////////////
#endregion

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using MetaCollection.Framework;
using MetaCollection.Framework.Model;
using System.Security;

namespace MetaCollection.ContentService.WebDav.Methods
{
	/// <summary>
	/// Provides support for the DELETE http verb on items in the collection.
	/// </summary>
	public static class Delete
	{
		/// <summary>
		/// Processes the DELETE request on an item.
		/// </summary>
		/// <param name="context">The context.</param>
		public static void Respond(DavContext context, IRequestHandler handler)
		{
			if (context == null)
				throw new ArgumentNullException("context");
			if (handler == null)
				throw new ArgumentNullException("handler");

			IItemInstance item = context.Item as IItemInstance;

			if (item == null)
				throw new Http.ClientException(Http.ClientErrorStatus.NotFound);

			try
			{
				if (String.IsNullOrEmpty(context.Request.SpecificVersion))
				{
					handler.ItemRequest(context.User, RequestTypes.DeleteItem, item.Href);
				}
				else if (context.Request.SpecificVersion.Equals("latest", StringComparison.OrdinalIgnoreCase))
				{
					handler.ItemRequest(context.User, RequestTypes.DeleteItem | RequestTypes.VersionLatest, item.Href);
				} 
				else
				{
					handler.ItemRequest(context.User, RequestTypes.DeleteItem | RequestTypes.VersionSpecific, item.Href, Convert.ToInt32(context.Request.SpecificVersion));
				}

			}
			catch (SecurityException ex)
			{
				if (ex.PermissionState.Contains("Delete"))
					throw new Http.ClientException(Http.ClientErrorStatus.Forbidden, "Delete Item Failed - Insufficient rights in current context.", ex);
				throw; // we got something we were not expecting here...
			}
			// TODO : wrap this in a mult-response code 207 webdav wrapper.
			context.Response.SetStatus((int)Http.SuccessStatus.NoContent, "Request Successful");
		}
	}
}
